const globalConfig = require("../../config");
const aMapSdk = require("./amap-wx");
// 高德地图
function aMapClass(key) {
  this.key = key || globalConfig.mapKey;
  this.amapInstance = null;
  this.init()
}
// 初始化 在页面或者组件里面初始化  须在 onLoad or attached（可以获取当前实例的生命周期）
aMapClass.prototype.init = function () {
  if (!this.amapInstance) {
    this.amapInstance = new aMapSdk.AMapWX({ key: this.key });
  }
  return this.amapInstance;
};
// 解析地址坐标   传经纬度
aMapClass.prototype.resolveLocation = function (resolveLocation) {
  return new Promise((resolve, reject) => {
    let location = "";
    if (coordinate) {
      const { longitude, latitude } = resolveLocation;
      location = `${longitude},${latitude}`;
    }
    this.amapInstance.getRegeo({
      location,
      success(data) {
        //成功回调
        resolve(data[0]);
      },
      fail(info) {
        //失败回调
        reject(info);
      },
    });
  });
};
// 获取当前位置相关信息
aMapClass.prototype.getLocation = function () {
  return new Promise((resolve, reject) => {
    // 获取定位坐标
    wx.getLocation({
      type: "gcj02",
      isHighAccuracy: true,
      highAccuracyExpireTime: 1500,
      success: (res) => {
        this.amapInstance.resolveLocation(res)
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

module.exports = {
  aMapClass,
};
